package com.jemaa.news.app.impl;

import java.io.UnsupportedEncodingException;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.mail.MailException;
import org.springframework.mail.MailSendException;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;

import com.jemaa.news.app.Contact;
import com.jemaa.news.app.NotificationService;
import com.jemaa.news.exceptions.JemaaException;


public class EmailNotificationService implements NotificationService {

	protected final Log logger = LogFactory.getLog(getClass());
	
	private JavaMailSender mailSender;  
	
	public EmailNotificationService(JavaMailSender mailSender){  
		this.mailSender = mailSender;  
	}  

	public void sendNotification(String message, Exception exception) {  
		try{  
			MimeMessage msg = mailSender.createMimeMessage();
			MimeMessageHelper helper = new MimeMessageHelper(msg);
			helper.setFrom("notificationjemaa@gmail.com");
			helper.setSubject("Notificaion d'erreur sur Jemaa : " + exception.getMessage());
			helper.setTo("contactjemaa@gmail.com");
			helper.setText("Application Message - " + message + " : " + exception.getMessage(), true);
			mailSender.send(msg);
			} catch(MailException e) {  
				logger.error("Impossible d'envoyer le mail de notification d'exception : "+message, e);
			} catch (MessagingException e) {
				logger.error("Impossible d'envoyer le mail de notification d'exception : "+message, e);
			}	  
	}

	public void sendContact(Contact contact) throws JemaaException {
		try {
			MimeMessage message = mailSender.createMimeMessage();
			MimeMessageHelper helper = new MimeMessageHelper(message);
			helper.setFrom(contact.getAddress(), contact.getAuthor());
			helper.setSubject("Contact via Jemaa : " + contact.getSubject());
			helper.setTo("contactjemaa@gmail.com");
			helper.setText(contact.getMessage(), true);
			mailSender.send(message);
		} catch (UnsupportedEncodingException e) {
			logger.error("Impossible d'envoyer le mail de notification du contact : "+contact.getSubject(), e);
			throw new JemaaException("Impossible d'envoyer le mail de notification du contact : "+contact.getSubject(), e);
		} catch (MessagingException e) {
			logger.error("Impossible d'envoyer le mail de notification : "+contact.getSubject(), e);
			throw new JemaaException("Impossible d'envoyer le mail de notification : "+contact.getSubject(), e);
		} catch (MailSendException e) {
			logger.error("Impossible d'envoyer le mail de notification : "+contact.getSubject(), e);
			throw new JemaaException("Impossible d'envoyer le mail de notification : "+contact.getSubject(), e);
		}
	}

	

}
